using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using Utilities;

namespace code_commenter {
	public partial class Form1 : Form {
		globalKeyboardHook gkh = new globalKeyboardHook();
        bool controlKeyDown = false;

        const string PROJECTS_FILE = "projects.txt";
        const string NAMES_FILE = "names.txt";

        const Keys singleLineKey = Keys.PageUp;
        const Keys multiLineKey = Keys.PageDown;


        [DllImport("user32.dll")]
        static extern int GetForegroundWindow();

        [DllImport("user32.dll")]
        static extern int GetFocus();

        [DllImport("user32.dll")]
        static extern int GetActiveWindow();

        [DllImport("user32.dll")]
        static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach);

        [DllImport("kernel32.dll")]
        static extern uint GetCurrentThreadId();

        [DllImport("user32.dll")]
        static extern uint GetWindowThreadProcessId(int hWnd, int ProcessId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
        static extern int SendMessage(int hWnd, int Msg, int wParam, StringBuilder lParam);

        const int WM_GETTEXT = 13;



		public Form1() 
        {
            InitializeComponent();
            StreamReader sr;
            if (File.Exists(PROJECTS_FILE))
            {
                sr = File.OpenText(PROJECTS_FILE);
                while (!sr.EndOfStream)
                {
                    comboBoxProject.Items.Add(sr.ReadLine());
                }
                sr.Close();
            }

            if (File.Exists(NAMES_FILE))
            {
                sr = File.OpenText(NAMES_FILE);
                while (!sr.EndOfStream)
                {
                    comboBoxName.Items.Add(sr.ReadLine());
                }
                sr.Close();
            }            
		}

		private void Form1_Load(object sender, EventArgs e) 
        {
            gkh.HookedKeys.Add(Keys.LControlKey);
            gkh.HookedKeys.Add(singleLineKey);
            gkh.HookedKeys.Add(multiLineKey);
			gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
			gkh.KeyUp += new KeyEventHandler(gkh_KeyUp);
		}

		void gkh_KeyUp(object sender, KeyEventArgs e) 
        {
            if (e.KeyCode == Keys.LControlKey)
            {
                controlKeyDown = false;
                e.Handled = false;
                return;
            }
            e.Handled = false;
		}

		void gkh_KeyDown(object sender, KeyEventArgs e) 
        {
            if (e.KeyCode == Keys.LControlKey)
            {
                controlKeyDown = true;
                e.Handled = false;
                return;
            }

            if (!controlKeyDown)
            {
                e.Handled = false;
                return;
            }

            SendKeys.SendWait("^c");

            if (Clipboard.ContainsText())
            {
                // add details to .txt files
                if (!comboBoxProject.Items.Contains(comboBoxProject.Text))
                { // need to add to the file
                    StreamWriter sw = new StreamWriter(PROJECTS_FILE, true);
                    sw.WriteLine(comboBoxProject.Text);
                    sw.Close();
                    comboBoxProject.Items.Add(comboBoxProject.Text);
                }
                if (!comboBoxName.Items.Contains(comboBoxName.Text))
                { // need to add to the file
                    StreamWriter sw = new StreamWriter(NAMES_FILE, true);
                    sw.WriteLine(comboBoxName.Text);
                    sw.Close();
                    comboBoxName.Items.Add(comboBoxName.Text);
                }

                DateTime dateTime = DateTime.Now;

                StringBuilder sDate = new StringBuilder();
                sDate.AppendFormat("{0:dd/MM/yyyy HHmm}", dateTime);

                String text = Clipboard.GetText();

                if (e.KeyCode == singleLineKey)
                    text = text + " \t// " + comboBoxName.Text + " - '" + comboBoxProject.Text + "' - " + sDate;

                if (e.KeyCode == multiLineKey)
                    text = "// " + comboBoxName.Text + " START - '" + comboBoxProject.Text + "' - " + sDate + "\r\n" + text + "\r\n// " + comboBoxName.Text + " END";

                Clipboard.SetText(text);
                SendKeys.Send("^v");

            }
            e.Handled = true;
            //getChildWindowText();
		}

        private void getChildWindowText()
        {
            StringBuilder builder = new StringBuilder(500);

            uint remoteThreadId = GetWindowThreadProcessId(GetForegroundWindow(), 0);
            uint currentThreadId = GetCurrentThreadId();

            //AttachTrheadInput is needed so we can get the handle of a focused window in another app
            AttachThreadInput(currentThreadId, remoteThreadId, true);
            //Get the handle of a focused window
            int focused = GetFocus();
            //Now detach since we got the focused handle
            AttachThreadInput(currentThreadId, remoteThreadId, false);

            //Get the text from the active window into the stringbuilder
            SendMessage(focused, WM_GETTEXT, builder.Capacity, builder);
            MessageBox.Show(builder.ToString()+ " " + focused);
        }

        private void comboBoxName_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
	}
}